package com.bruce.common;

import android.app.Activity;

import java.util.Stack;

/**
 * activity堆栈管理类
 *
 * @author LiXiaolong
 * @version 1.0
 * @since 2013-5-6 下午1:44:48
 */
public class ActivityMgr {

    private static Stack<Activity> activityStack;
    private static ActivityMgr instance;

    public static ActivityMgr getInstance() {
        synchronized (ActivityMgr.class) {
            if (instance == null) {
                instance = new ActivityMgr();
            }
        }
        return instance;
    }

    /**
     * 退出栈顶Activity
     */
    public boolean popActivity(Class<?> cls) {
        Activity activity;
        if (activityStack != null && !activityStack.empty()) {
            int count = activityStack.size();
            for (int i = 0; i < count; i++) {
                activity = activityStack.elementAt(i);
                if (activity != null) {
                    Class<?> acti = activity.getClass();
                    if (acti.equals(cls) && !activity.isFinishing()) {
                        activity.finish();
                        activityStack.remove(activity);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 退出栈中所有Activity
     */
    private void popAllActivity() {
        Activity activity;
        if (activityStack != null && !activityStack.empty()) {
            int count = activityStack.size();
            for (int i = 0; i < count; i++) {
                activity = activityStack.elementAt(i);
                if (activity != null && !activity.isFinishing()) {
                    activity.finish();
                }
            }
        }
        if (activityStack != null && !activityStack.empty()) {
            activityStack.clear();
            activityStack = null;
        }
    }

    /**
     * 将当前Activity推入栈中
     *
     * @param activity 当前Activity
     */
    public void pushActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }

    public void popActivity(Activity activity) {
        if (activityStack != null && activityStack.contains(activity)) {
            activityStack.remove(activity);
        }
    }

    /**
     * 退出应用
     */
    public void exitApp() {
        // 退出所有页面
        popAllActivity();
        System.exit(0);
    }

}